const express = require('express');
const fs = require('fs');
const path = require('path');
const formidableMiddleware = require('express-formidable');
const consola = require('consola');
const bodyParser = require('body-parser');
const multer = require('multer'); // for parsing multipart/form-data
const mongoose = require('mongodb');
const ObjectId = require('mongodb').ObjectId;

const {
  format,
  fromNow
} = require('silly-datetime'); // 格式化生成时间
const mongoUrl = "mongodb://localhost:27017/";
const upload = multer()
const {
  Nuxt,
  Builder
} = require('nuxt')
const app = express()



// 设置跨域
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000"); //运行跨域   来之http://localhost:3000域名的
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header('Access-Control-Allow-Credentials', true); //运行表头带cookie参数
  res.header("X-Powered-By", ' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");


  next();
});

app.use(formidableMiddleware());
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
  extended: true
})); // for parsing application/x-www-form-urlencoded



// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host,
    port
  } = nuxt.options.server

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

// 详情页向数据库获取数据
app.get('/details/content/:id', (req, res, next) => {
  let id = ObjectId(req.params.id);
  mongoose.connect(mongoUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, function (err, db) {
    if (err) throw err;
    const dbo = db.db("chunfengxiao");
    dbo.collection("article").find({
      "_id": id
    }).toArray(function (err, result) { // 返回集合中所有数据
      if (err) throw err;
      res.send(result)
      db.close();
    });
  });
});



// 首页向数据库获取数据
app.get('/article/list/:id', upload.array(), (req, res, next) => {
  mongoose.connect(mongoUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, function (err, db) {
    if (err) throw err;
    const dbo = db.db("chunfengxiao");
    let idObj = '';
    if (req.params.id == '热门推荐') {
      idObj = {}
    } else {
      idObj = {
        "type": req.params.id
      }
    }
    dbo.collection("article").find(idObj).toArray((err, result) => { // 返回集合中所有数据
      if (err) throw err;
      res.send(result)
      db.close();
    });
  });
});


// 文章向数据库传入数据
app.post('/details/addArticle', upload.array(), (req, res, next) => {
  mongoose.connect(mongoUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, function (err, db) {
    if (err) throw err;
    const dbo = db.db("chunfengxiao");
    const myobj = req.body;
    dbo.collection("article").insertOne(myobj, (err, result) => { // 返回集合中所有数据
      if (err) throw err;
      res.json(result);
      db.close();
    });
  });
});


// 登录
app.post('/login', upload.array(), (req, res, next) => {
  mongoose.connect(mongoUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, function (err, db) {
    if (err) throw err;
    const dbo = db.db("chunfengxiao");
    const loginInt = req.body;
    const getName = {
      "usename": loginInt.usename
    }
    dbo.collection("register").find(getName).toArray((err, result) => { // 返回集合中所有数据
      if (err) throw err;
      if (result !== undefined && result[0] !== undefined && result[0].usename !== undefined && result[0].usename === loginInt.usename) {
        res.json('true');
      } else {
        res.json('false')
      }
      db.close();
    });
  });
});

// 注册
app.post('/register', upload.array(), (req, res, next) => {
  mongoose.connect(mongoUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, function (err, db) {
    if (err) throw err;
    const dbo = db.db("chunfengxiao");
    const registerInt = req.body;
    dbo.collection("register").insertOne(registerInt, (err, result) => { // 返回集合中所有数据
      if (err) throw err;
      res.json(result);
      db.close();
    });
  });
});

// 图片上传
app.post('/uploadImg', function (req, res, next) {

  let object = req.files;
  let oldPath, extname;
  for (const key in object) {
    if (object.hasOwnProperty(key)) {
      const element = object[key];
      oldPath = element.path //fileName就是我们刚在前台模板里面配置的后台接受的名称；
      extname = element.name //获取图片名称
    }
  }
  let dir = "./assets/img/";

  //创建文件夹
  let createFileDirectory = function (dir) {
    try {
      //检测文件夹是否存在，不存在抛出错误
      fs.accessSync(dir);
    } catch (error) {
      //创建文件夹
      fs.mkdirSync(dir);
    }
  }

  //先创建路径在保存
  createFileDirectory(dir);


  //新的路径由组成：原父路径 + 拓展名
  let newPath = dir + extname;

  //把之前存的图片换成真的图片的完整路径
  let readStream = fs.createReadStream(oldPath);
  let writeStream = fs.createWriteStream(newPath);
  readStream.pipe(writeStream);
  readStream.on('end', function () {
    fs.unlinkSync(oldPath);
  });
});



start()
